const _ = require('lodash');

const prefix = '/api/notify';
module.exports = app => {
    const {router, middleware} = app;

    /**消息列表*/
    router.get(prefix, middleware.api(), async ctx => {
        const {page, limit, offset} = ctx.service.page.page();

        const total = await app.model.Message.count({where: {type: 1}});
        const list = await app.model.Message.findAll({
            order: [['id', 'desc']],
            total,
            limit,
            offset,
            where: {type: 1},
            include: [{model: app.model.User.unscoped(), as: 'from', attributes: ['username']}]
        });

        ctx.body = {list, total, page};
    });

    /**读取内容*/
    router.get(prefix + '/:id', middleware.api(), async ctx => {
        ctx.body = await app.model.Message.findOne({where: {id: ctx.params.id, type: 1}});
    });

    /**删除短消息*/
    router.del(prefix + '/:id', middleware.api(2), async ctx => {
        app.model.Message.destroy({where: {id: ctx.params.id, type: 1}});
        ctx.body = 'ok';
    });

    /**发公告**/
    router.post(prefix, middleware.api(2), async ctx => {
        let {title, content} = ctx.request.body;
        ctx.body = await app.model.Message.create({title, content, type: 1, from_id: ctx.user.id});
    });
};